// Modules to control application life and create native browser window
const { app, BrowserWindow, Menu, ipcMain } = require('electron')
const path = require('path')
const fs = require('fs');
const { decode } = require('querystring');
const csv = require('csvtojson')
var isMax = false
var originData
var flag = false
function createWindow () {
  Menu.setApplicationMenu(null)
  var mainWindow = new BrowserWindow({
    width: 1100,
    height: 800,
    frame: false,
    transparent: true,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true
    }
  })
  // 开启调试窗口
  // mainWindow.webContents.openDevTools()
  ipcMain.on('smaller', () => {
    mainWindow.minimize()
  })
  ipcMain.on('bigger', () => {
    if (isMax) {
      mainWindow.setSize(1100, 800)
      mainWindow.center()
      isMax = !isMax
    }
    else {
      mainWindow.maximize()
      isMax = !isMax
    }
  })
  ipcMain.on('close', () => {
    mainWindow.close()
  })
  ipcMain.on('again', () => {
    mainWindow.webContents.send('originData', originData)
  })
  ipcMain.on('loves', (event, e) => {
    var contentLoves = "name,author,url,flag\n"
    e.forEach((arg) => {
      contentLoves += arg.name + ',' + arg.author + ',' + arg.url + ',' + arg.flag + '\n'
    })
    fs.writeFileSync("./static/csv/loveSongs.csv", contentLoves, () => { })
    mainWindow.close()
  })
  mainWindow.loadFile('index.html')
  // 加载初始数据
  ipcMain.on('start', (event) => {
    csv().fromFile('./static/csv/loveSongs.csv').then((data) => {
      originData = data
      mainWindow.webContents.send('originData', data)
    })
  })
  mainWindow.on('close', (e) => {
    if (!flag) {
      // 阻止默认关闭事件，等喜欢歌曲全部写入后再关闭
      e.preventDefault()
      mainWindow.webContents.send('willingClose')
      flag = true
    }
    else {
      mainWindow = null
    }
  })
}
app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

